<?php
/**
 * Created by PhpStorm.
 * User: lenovo
 * Date: 2020/2/5
 * Time: 22:05
 */

namespace app\api\controller;


use app\api\Base2Controller;

class Fulogin extends Base2Controller
{
    /**
     * 登录
     */
    public function fulogin()
    {
        if (empty(input('phone')) || empty(input('password')))
        {
            return json_fail_return('请正确输入信息');
        }
        $model = model('fupersonal');
        $token_model=model('futoken');
        $data =[
            'phone'=>input('phone'),
            'password'=>md5(input('password')),
        ];
        $data = $model->info($data);
        if (empty($data)){
            return json_fail_return('账号或密码错误');
        }
        if (!$data['status']){
            return json_fail_return('当前账号未启用,请联系后台管理员开通权限');
        }
        $token = $this->buildAccessToken();
        $token_info = $token_model->getToken(['user_id'=>$data['id']]);
        if($token_info) {
            $token_model->updateById(['token' => $token, 'expire_time' => time() + 24 * 60 * 60 * 10, 'updated_at' => date('Y-m-d H:i:s')], $token_info['id']);
        }else{
            $add_data = array(
                'user_id'=>$data['id'],
                'token'=>$token,
                'expire_time'=>time()+24*60*60*10,
                'created_at'=>date('Y-m-d H:i:s'),
                'updated_at'=>date('Y-m-d H:i:s')
            );
            if(!$token_model->addToken($add_data)){
                return json_fail_return('token生成失败,请重试');
            }
        }
        $login_num = $data['login_num']+1;
        $bool = $model->edit(['id'=>$data['id']],
            [
                'login_num'=>$login_num,
                'login_time'=>date('Y-m-d H:i:s',time())
            ]);
        //获取服务运营商的信息
        $result = array(
            'token'=>$token,
            'login_url' => 'http://three.douyinhot.com/index.php'
        );

        $userid = $data['id'];
        $fuwu_data['fuwu_longitude'] = input('longitude');
        $fuwu_data['fuwu_latitude'] = input('latitude');
        $fuwu_data['clientid'] = input('clientid');
        db('fuwu_personal')->where(['id'=>$userid])->update($fuwu_data);

        //新用户登录赠送积分
        if($data['login_num'] == 0 && $data['prevtype'] == 3) #客户邀请服务人员
        {
            #通过上级邀请人的id，送积分
            $superior_info = db('member')->where(['member_id'=>$data['prev']])->find();
            
            //增加积分
            $config = db('config')->where('code', 'purchase_goods')->find();
            $points = $superior_info['member_points'] + $config['value'];
            db('member')->where(['member_id'=>$data['prev']])->update(['member_points'=>$points]);

            #日志
            $log_data = [
                'pl_memberid' => $superior_info['member_id'],
                'pl_membername' => $superior_info['member_name'],
                'pl_points' => $config['value'],
                'pl_addtime' => time(),
                'pl_desc' => '邀请新服务人员[' . $data['phone'] . ']注册',
                'pl_stage' => 'sinviter'
            ];
            db('pointslog')->insertGetId($log_data);
        }elseif($data['login_num'] == 0 && $data['prevtype'] == 4){ #服务人员邀请服务人员
            #通过上级邀请人的id， 送余额
            $superior_info = db('fuwu_personal')->where(['id'=>$data['prev']])->find();

            //增加余额
            $config = db('config')->where('code', 'service_invitation')->find();
            $points = $superior_info['money'] + $config['value'];
            db('fuwu_personal')->where(['id'=>$data['prev']])->update(['money'=>$points]);

             #日志
             $log_data = [
                'member_id' => $superior_info['id'],
                'type' => 1,
                'name' => $superior_info['phone'],
                'money' => $config['value'],
                'surplus_money' => $points,
                'money_type' => 2,
                'addtime' => time(),
                'desc' => '邀请新服务人员[' . $data['phone'] . ']注册',
            ];
            db('money_log')->insertGetId($log_data);
        }

        return json_success_return($result, '登录成功');

    }

    /**
     * 退出
     */
    public function fulogout()
    {
        $tokenmodel = model('futoken');
        $bool = $tokenmodel->updateById(['expire_time'=>time()],$this->tokeid);
        if ($bool){
            return json_success_return([],'退出成功');
        }else{
            return json_fail_return('退出失败');
        }
    }

    /**
     * 注册
     */
    public function register()
    {
//        !($avtar = input('avtar')) ||
        if ( !($skillid = input('skillid')) ||!($phone = input('phone'))
        ||!($password = input('password')) || !($password2 = input('password2')) || !($code = input('code')))
        {
            return json_fail_return('请正确输入信息');
        }
        // if (!checkCode($phone,$code))
        // {
        //     return json_fail_return('验证码错误');
        // }
        if ($password != $password2)
        {
            return json_fail_return('两次密码输入不一致');
        }

        $model = model('fupersonal');
        $info = $model->info(['phone'=>$phone],'id');
        if ($info)
        {
            return json_fail_return('该手机号已注册');
        }
        $data = [];
        $prev = [];
        $prev['prevtype'] = 0;
        if (($prevcode = input('prevcode')))
        {
            $prev = $model->getMember($prevcode);
            if (!$prev['prev']){
                return json_fail_return('该邀请码错误');
            }
            $data['prevcode'] = $prevcode;
            $data['prev'] = $prev['prev'];
            $data['prevtype'] = $prev['prevtype'];
        }
        $code = model('member')->createInviteCode();
        $gradeid  = model('fugrade')->getList(['status'=>1],'id',0,'id asc');
        $data2 = [
            'avtar' => 'http://33wang.douyinhot.com/46f5b202003131520417317.png',
            'skillid'=>$skillid,
            'password'=>md5($password),
            'gradeid'=>$gradeid[0]['id'],
            'phone'=>$phone,
            'code'=>$code,
            'status'=>1,
            'created_at'=>date('Y-m-d H:i:s',time()),
            'updated_at'=>date('Y-m-d H:i:s',time()),
        ];
        #生成二维码
        $result = scerweima1('https://www.baidu.com','fuwu_'.$code,$data2['avtar']);

        #生成海报
        $config = array(
            'text'=>array(
                array(
                  'text'=>$code,
                  'left'=>480,
                  'top'=>610,
                  'fontPath'=>'code/SIMYOU.TTF',     //字体文件
                  'fontSize'=>45,             //字号
                  'fontColor'=>'0,0,0',       //字体颜色
                  'angle'=>0,
                )
              ),
           'image'=>array(
                array(
                  'url'=> $result['code'],     //二维码资源
                  'stream'=>0,
                  'left'=>330,
                  'top'=>916,
                  'right'=>0,
                  'bottom'=>0,
                  'width'=>478,
                  'height'=>478,
                  'opacity'=>100
                )
             ),
             'background'=>'http://33wang.douyinhot.com/f07e9202003151744241290.png'          //背景图
        );
        $filename = 'code/'.time().'.jpg';
        createPoster($config,$result['code']);
        
        #纯二维码
        $data2['fuwu_img_code'] = "http://three.douyinhot.com/" . $result['img_code'];

        #海报二维码
        $data2['fuwu_code'] = "https://three.douyinhot.com/" . $result['code'];

        $id = $model->add(array_merge($data,$data2));
        //生成极光账号
        $post = [
            'username' => 'fuwu' . $phone,
            'password' => $password,
            'nickname' => $phone,
            'avatar' =>   '',
            'signature' => '',
        ];
        JmRegist($post);
        
        //生成提成运营商账号
        $seller_id = $model->setService($phone,$password,$code,$id,$prev['prevtype'],$prevcode);
        db('fuwu_personal')->where(['id'=>$id])->update(['operators_id'=>$seller_id]);
        if ($id){
            // //处理积分问题
            // if (($prevcode = input('prevcode'))) {
            //     if ($prev['prev']) {
            //         $bool = $model->updateYue($prev['prev'], $prev['prevtype']);
            //         if ($bool){
            //             return json_success_return([],'注册成功');
            //         }else{
            //             return json_success_return([],'注册成功');
            //         }
            //     }
            // }
            return json_success_return([],'注册成功');
        }else{
            return json_fail_return([],'注册失败');
        }
    }

    /**
     * 技能
     */
    public function getskillid()
    {
        $data = model('fuskill')->getList(['status'=>1],'id,name');
        return json_success_return($data);
    }
}